package dao.impl;

import dao.IUserDao;
import entity.Users;
import until.DButil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl extends DButil implements IUserDao {
    Connection conn=null;
    PreparedStatement pst=null;
    ResultSet rs=null;
    @Override
    public int register(String uname, String pwd) {
        conn=getCon();

        int len=0;
        try {
            String sql1="select col_uname from tb_user where col_uname=?";
            pst=conn.prepareStatement(sql1);
            pst.setString(1,uname);
           if (pst.executeQuery().next()){
               len=0;
           }else {
               String sql2="insert into tb_user(col_uname,col_upwd,col_udel) values(?,?,1)";
               pst=conn.prepareStatement(sql2);
               pst.setString(1,uname);
               pst.setString(2,pwd);
               len=pst.executeUpdate();
           }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            clsAll(conn,pst,null);
        }
        return len;
    }

    @Override
    public Users login(String uname, String pwd) {
        Users users=null;
        conn=getCon();
        try {
            String sql="select * from tb_user where col_uname=? and col_upwd=?";
            pst=conn.prepareStatement(sql);
            pst.setString(1,uname);
            pst.setString(2,pwd);
            rs=pst.executeQuery();
            if (rs.next()){
                users=new Users();
                users.setUid(rs.getInt(1));
                users.setUname(rs.getString(2));
                users.setUpwd(rs.getString(3));
                users.setUdel(rs.getInt(4));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            clsAll(conn,pst,rs);
        }
        return users;
    }

    @Override
    public Users getUid(String name) {
        Users users=null;
        conn=getCon();
        try {
            String sql="select * from tb_user where col_uname=?";
            pst=conn.prepareStatement(sql);
            pst.setString(1,name);
            rs=pst.executeQuery();
            if(rs.next()){
                users=new Users();
                users.setUid(rs.getInt(1));
                users.setUname(rs.getString(2));
                users.setUpwd(rs.getString(3));
                users.setUdel(rs.getInt(4));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            clsAll(conn,pst,rs);
        }
        return users;
    }


}
